import { globalToken, globalHost, globalNotLoginToken } from './constant'
import { getCurrentPageUrlWithArgs } from './util'

// const app = getApp();

export default class Http {
  static request(method, url, data, showLoading) {
    showLoading &&
      wx.showLoading({
        title: `${
          url.indexOf('/ai/order/text_to_order') ? '加载中' : '语义解析中'
        }`
      })

    return new Promise((resolve, reject) => {
      const header = this.createAuthHeader()
      wx.request({
        url: globalHost + encodeURI(url),
        method,
        header,
        data,
        success: (res) => {
          wx.hideLoading()
          // 微信状态校验
          const wxCode = res.statusCode
          if (wxCode !== 200) {
            console.error('服务端请求错误', res)
            this.handleHttpException(res)
            reject(res)
          } else {
            // 服务端状态校验
            const serverData = res.data
            const { code } = serverData
            if (false && code !== 200000) {
              this.showTips(res)
              this.handleErrorCode(code)
              reject(serverData)
            } else {
              // 登录token存储
              if (url.indexOf('usercenter/app/login/sms') > -1) {
                const token =
                  res.header['Login-Token'] || res.header[globalToken]
                console.log(globalToken)
                wx.setStorageSync(globalToken, token)
              }
              if (
                serverData.result &&
                Object.prototype.hasOwnProperty.call(serverData.result, 'Code')
              ) {
                //  腾讯返回的code
                const { Code } = serverData.result
                if (Code === 0) {
                  resolve(serverData)
                } else {
                  reject(serverData)
                }
              } else {
                //  永辉内部result 服务端返回数据字段
                resolve(serverData)
              }
            }
          }
        },
        fail: (res) => {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '网络请求失败',
            showCancel: false,
            success(successres) {
              console.log(successres)
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.error('网络请求发起失败', res)
          reject(res)
        }
      })
    })
  }

  /**
   * 错误提示
   */
  static showTips(res) {
    const tip = res.data.code === 412999 ? '请登录' : res.data.message
    wx.showToast({
      title: tip,
      icon: 'none',
      // image: '/images/icon/error.png',
      mask: true,
      duration: 2000
    })
  }

  /**
   *  业务错误code处理
   */

  static handleErrorCode(code) {
    // 600201
    switch (code) {
    case 600207:
      this.handleError600207Code(code)
      break
    case 600201:
      this.handleError600201Code(code)
      break
    default:
      console.info('其他错误', code)
    }
  }

  /**
   * 微信错误处理器
   */
  static handleHttpException(res) {
    const status = res.statusCode
    switch (status) {
    case 403:
      this.handleHttp403Exception(res)
      break
    case 500:
      this.handleHttp500Exception(res)
      break
    default:
      console.info(`其他错误-状态码${status}`, res)
    }
  }

  /**
   * 登录超时
   */
  static handleError600207Code() {
    const backUrl = getCurrentPageUrlWithArgs()
    wx.showToast({
      tilte: '登录超时'
    })
    wx.removeStorageSync(globalToken)
    wx.setStorageSync(globalToken, globalNotLoginToken)
    wx.navigateTo({
      url: `/pages/login/index/login?backUrl=${backUrl}`
    })
  }

  /**
   * 未登录
   */

  static handleError600201Code() {
    const backUrl = getCurrentPageUrlWithArgs()
    wx.showToast({
      tilte: '未登录'
    })
    wx.navigateTo({
      url: `/pages/login/index/login?backUrl=${backUrl}`
    })
  }

  /**
   * 403无权限错误
   */
  static handleHttp403Exception(res) {
    console.error(`403-权限错误：${res.data.message}`)
  }

  /**
   * 500内部错误
   */
  static handleHttp500Exception(res) {
    console.error(`500-服务器内部错误：${res.data.message}`)
  }

  /**
   * 构造权限头部
   */
  static createAuthHeader() {
    const loginToken = wx.getStorageSync(globalToken)
    const header = {}
    if (loginToken) {
      header[globalToken] = loginToken
    }
    return header
  }

  static get(url, data, showLoading) {
    return this.request('GET', url, data, showLoading)
  }

  static put(url, data, showLoading) {
    return this.request('PUT', url, data, showLoading)
  }

  static post(url, data, showLoading) {
    return this.request('POST', url, data, showLoading)
  }

  static delete(url, data, showLoading) {
    return this.request('DELETE', url, data, showLoading)
  }
}
